package com.suning.sawp.in.controller.model;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.suning.sawp.constants.ExportConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.constants.ModelClusterErrorConstants;
import com.suning.sawp.dto.common.EmployeeInfo;
import com.suning.sawp.dto.common.QueryClusterInfoList;
import com.suning.sawp.dto.common.QueryResult;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.oss.ExportTaskDto;
import com.suning.sawp.exception.SawpException;
import com.suning.sawp.in.controller.DjBaseController;
import com.suning.sawp.in.controller.MyGsonView;
import com.suning.sawp.in.filter.RequestUserHolder;
import com.suning.sawp.intf.model.CommInfoBean;
import com.suning.sawp.intf.model.ModelCommClusterVo;
import com.suning.sawp.intf.model.ModelErrorConstant;
import com.suning.sawp.intf.model.ModelManageService;
import com.suning.sawp.service.impl.model.ModelManageServiceImpl;
import com.suning.sawp.service.util.ExportFileUtil;

@RequestMapping("/adminPage/model")
@Controller
public class ModelClusterController extends DjBaseController{

    @Resource
    ModelManageService modelManageService;
    
    @Resource
    MongoTemplate mongoTemplate;
    
    @Resource
    ExportFileUtil exportFileUtil;
    
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);
    
    /**
     * 
     * 功能描述: 查询簇列表<br>
     * 〈功能详细描述〉
     *
     * @param branchCode
     * @param commCode
     * @param isCluster
     * @param regionCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/commCluster.do")
    public MyGsonView queryModelClusterList(String branchCode,String commInfo,Integer isCluster,Integer pageSize,Integer pageNo){
        ReturnMsg<QueryClusterInfoList> ret = new  ReturnMsg<QueryClusterInfoList>();
        try{
//            ret = modelManageService.queryModelClusterList(commInfo, pageSize, pageNo);
            ret = modelManageService.queryModelClusterInfoList(commInfo, pageSize, pageNo);
        }catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999,ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(String.format("ModelClusterController queryModelClusterList error param(branchCode:%s,commInfo:%s,isCluster:%s)", branchCode,commInfo,isCluster),e);
        }
        return setGsonView(ret);
    }
    /**
     * 
     * 功能描述:查询簇下商品列表 <br>
     * 〈功能详细描述〉
     *
     * @param branchCode
     * @param clusterId
     * @param commCode
     * @param pageNo
     * @param pageSize
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryCommList.do")
    public MyGsonView queryCommList(String branchCode,Integer clusterId,String commCode,Integer pageNo,Integer pageSize){
        ReturnMsg<QueryResult<CommInfoBean>> ret = new ReturnMsg<QueryResult<CommInfoBean>>();
        try{
            ret = modelManageService.queryClusterComm(clusterId, commCode, branchCode, pageSize, pageNo);
        }catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999,ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(String.format("ModelClusterController queryCommList param(branchCode:%s,clusterId:%s,commCode:%s)", branchCode,clusterId,commCode),e);
        }
        return setGsonView(ret);
    }
    /**
     * 
     * 功能描述: 删除商品簇<br>
     * 〈功能详细描述〉
     *
     * @param branchCode
     * @param clusterId
     * @param commCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/delCluster.do")
    public MyGsonView delCluster(String branchCode,Integer clusterId,String commCode){
        ReturnMsg<Integer> ret = new ReturnMsg<Integer>();
        try{
           ret =  modelManageService.deleteModelCluster(clusterId, commCode, branchCode);
        }catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999,ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(String.format("ModelClusterController delCluster param(branchCode:%s,clusterId:%s,commCode:%s)", branchCode,clusterId,commCode),e);
        }
        return setGsonView(ret);
    }
    /**
     * 
     * 功能描述: 查询推荐商品<br>
     * 〈功能详细描述〉
     *
     * @param commCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryRecommComm.do")
    public MyGsonView queryRecommComm(String commCode,String branchCode){
        ReturnMsg<List<ModelCommClusterVo>> ret = new ReturnMsg<List<ModelCommClusterVo>>();
        try{
            ret = modelManageService.queryRecommendComm(commCode,branchCode);
        }catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999,ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(String.format("ModelClusterController queryRecommComm param(commCode:%s)", commCode),e);
        }
        return setGsonView(ret);  
    }
    /**
     * 
     * 功能描述:添加簇商品<br>
     * 〈功能详细描述〉
     *
     * @param branchCode
     * @param commCode
     * @param mainCommCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @Deprecated
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping("/saveCluster.do")
    public MyGsonView addClusterComm(String branchCode,String commCode,String mainCommCode){
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        ReturnMsg ret = new ReturnMsg();
        try{
            ret = modelManageService.saveClusterComm(mainCommCode, commCode, branchCode, employeeInfo.getStaffId());
        }catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999,ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(String.format("ModelClusterController queryRecommComm param(commCode:%s)", commCode),e);
        }
        return setGsonView(ret);
    }
    /**
     * 
     * 功能描述: 簇商品管理导出<br>
     * 〈功能详细描述〉
     *
     * @param branchCode
     * @param commInfo
     * @param isCluster
     * @param index
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
//    @RequestMapping("/exptCommCluster.do")
    @Deprecated
    public void exptCommCluster(String branchCode, String commInfo, Integer isCluster, Integer index,
            HttpServletResponse response) {
        OutputStream ouputStream = null;
        try {
            Workbook workbook = modelManageService.exportCommCluster(branchCode, commInfo, isCluster, index);
            if (workbook == null) {
                response.setContentType("text/html; charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache");
                ouputStream = response.getOutputStream();
                ouputStream.write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E007)
                        .getBytes());
            } else {
                response.setContentType("application/x-download");
                // response.setHeader("Content-disposition", "attachment;filename=modelCluster_" + branchCode + "_"+
                // index +".xlsx");
                response.setHeader("Content-disposition", "attachment;filename=modelCluster.xlsx");
                ouputStream = response.getOutputStream();
                workbook.write(ouputStream);
            }
            
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException e) {
            LOGGER.error("exptCommCluster 导出excel出错", e);
        } catch (Exception e) {
            LOGGER.error("exptCommCluster 导出excel出错", e);
        } finally {
            modelManageService.endExportExcel();
        }
    }
    
    /**
     * 
     * 功能描述: 簇商品管理导出<br>
     * 〈功能详细描述〉
     *
     * @param branchCode
     * @param commInfo
     * @param isCluster
     * @param index
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/exptCommCluster.do")
    public void exptCommClusterEx(String branchCode, String commInfo, Integer isCluster, Integer index,
            HttpServletResponse response) {
        OutputStream ouputStream = null;
        try {
            ouputStream = response.getOutputStream();
            EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
            if (null == employeeInfo || StringUtils.isBlank(employeeInfo.getStaffId())) {
                LOGGER.error("exptCommClusterEx.Paramter is null. employeeInfo is null");
                ouputStream.write(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E001).getBytes());
                return;
            } else {
                String staffId = employeeInfo.getStaffId();
                String className = ModelManageServiceImpl.class.getName(); 
                String methodName = ExportConstants.ExportMethodName.EXPORT_COMM_CLUSTER_EX;
                @SuppressWarnings("unchecked")
                List<Object> params =  new ArrayList<Object>(Arrays.asList(staffId, branchCode, commInfo, isCluster, index));
                exportFileUtil.saveExportTask(staffId, className, methodName, params);
                ouputStream.write(ExportConstants.MODEL_EXPORT_TIPS_MAP.get(ExportConstants.TIP_T001).getBytes());
            }
        } catch (IOException e) {
            LOGGER.error("exptCommClusterEx failed.", e);
            throw new SawpException(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E999));
        } finally {
            try {
                if (null != ouputStream) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (IOException e) {
                LOGGER.error("exptCommClusterEx finally failed.", e);
            }
        }
    
        
        

    }
    
    /**
     * 导入簇商品
     * 
     * @param request
     * @return
     */
    @RequestMapping("/batchImportCluster.do")
    public MyGsonView batchImportClusterExcel(HttpServletRequest request) {
        MultipartRequest mutilRequest = (MultipartRequest) request;
        MultipartFile file = mutilRequest.getFile("firstExcel");
        ReturnMsg<List<String>> returnMsg = new ReturnMsg<List<String>>();

        // 参数错误
        if (file == null) {
            LOGGER.equals("batchImportClusterExcel. ExcelFile is null.");
            returnMsg.setError(ModelClusterErrorConstants.CLUSTER_ERR_PARAMS,
                    ModelClusterErrorConstants.MODEL_CLUSTER_ERR_MAP);
            return setGsonView(returnMsg);
        }
        ReturnMsg<List<String>> result = new ReturnMsg<List<String>>();
        try {
            result = modelManageService.batchImportClusterExcel(file);
        } catch (Exception e) {
            LOGGER.error("batchImportClusterExcel Error", e);
            result.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
        }
        return setGsonView(result);
    }
    
}
